package com.ms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.bind.annotation.*;

import com.ms.entity.Organizer;
import com.ms.service.inter.OrganizerService;
import com.ms.utils.SimpleTokenUtils;
import com.ms.utils.UserContext; // 添加这个导入
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/organizer")
public class OrganizerController {

    @Autowired
    private OrganizerService organizerService;

    /**
     * 举办方注册
     */
    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody Organizer organizer) {
        Map<String, Object> result = new HashMap<>();

        try {
            boolean success = organizerService.register(organizer);
            if (success) {
                result.put("success", true);
                result.put("msg", "注册成功");
            } else {
                result.put("success", false);
                result.put("msg", "注册失败，账号已存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "注册失败：" + e.getMessage());
        }

        return result;
    }

    /**
     * 举办方登录（账号密码）
     */
    @PostMapping("/login")
    public Map<String, Object> login(@RequestParam String account, @RequestParam String password) {
        Map<String, Object> result = new HashMap<>();

        Organizer organizer = organizerService.loginByAccount(account, password);
        if (organizer == null) {
            result.put("success", false);
            result.put("msg", "账号或密码错误，或账号已被禁用");
            return result;
        }

        // 生成Token保持登录状态
        String token = SimpleTokenUtils.generateToken(organizer);

        result.put("success", true);
        result.put("msg", "登录成功");
        result.put("token", token);
        result.put("organizer", organizer);

        return result;
    }

    /**
     * 举办方登出
     */
    @PostMapping("/logout")
    public Map<String, Object> logout(HttpServletRequest request) {
        String token = request.getHeader("token");
        Map<String, Object> result = new HashMap<>();

        if (token == null || token.isEmpty()) {
            result.put("success", false);
            result.put("msg", "token不存在");
            return result;
        }

        SimpleTokenUtils.removeToken(token);
        result.put("success", true);
        result.put("msg", "已登出");

        return result;
    }

    /**
     * 修改密码（需验证原密码）
     */
    @PostMapping("/updatePassword")
    public Map<String, Object> updatePassword(
            HttpServletRequest request,
            @RequestParam String oldPassword,
            @RequestParam String newPassword) {

        Map<String, Object> result = new HashMap<>();
        String token = request.getHeader("token");

        if (token == null || token.isEmpty()) {
            result.put("success", false);
            result.put("msg", "未登录");
            return result;
        }

        // 修改：使用更安全的方式获取当前用户
        Object currentUserObj = SimpleTokenUtils.getUserByToken(token);
        Organizer currentUser = null;
        if (currentUserObj instanceof Organizer) {
            currentUser = (Organizer) currentUserObj;
        }

        if (currentUser == null) {
            result.put("success", false);
            result.put("msg", "登录已过期，请重新登录");
            return result;
        }

        boolean success = organizerService.updatePassword(
                currentUser.getOrAccount(),
                oldPassword,
                newPassword);

        if (success) {
            result.put("success", true);
            result.put("msg", "密码修改成功");
            // 密码修改后建议重新登录
            SimpleTokenUtils.removeToken(token);
        } else {
            result.put("success", false);
            result.put("msg", "原密码错误，修改失败");
        }

        return result;
    }

    /**
     * 找回密码（通过联系方式验证）
     */
    @PostMapping("/retrievePassword")
    public Map<String, Object> retrievePassword(
            @RequestParam String account,
            @RequestParam String contact,
            @RequestParam String newPassword) {

        Map<String, Object> result = new HashMap<>();

        boolean success = organizerService.retrievePassword(account, contact, newPassword);
        if (success) {
            result.put("success", true);
            result.put("msg", "密码重置成功，请使用新密码登录");
        } else {
            result.put("success", false);
            result.put("msg", "账号或联系方式不匹配，重置失败");
        }

        return result;
    }

    /**
     * 获取当前登录的举办方信息
     */
    @GetMapping("/getCurrent")
    public Map<String, Object> getCurrentOrganizer(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        String token = request.getHeader("token");
        System.out.println("成功调用了该方法");
        if (token == null || token.isEmpty()) {
            result.put("success", false);
            result.put("msg", "未登录");
            return result;
        }

        // 修改：使用更安全的方式获取当前用户
        Object organizerObj = SimpleTokenUtils.getUserByToken(token);
        Organizer organizer = null;
        if (organizerObj instanceof Organizer) {
            organizer = (Organizer) organizerObj;
        }

        if (organizer == null) {
            result.put("success", false);
            result.put("msg", "登录已过期，请重新登录");
            return result;
        }

        result.put("success", true);
        result.put("data", organizer);
        return result;
    }





    /**
     * 更新举办方信息（仅允许更新账号、主办方名称、负责人、联系方式）
     */
    @PostMapping("/updateInfo")
    public Map<String, Object> updateOrganizerInfo(HttpServletRequest request,
                                                   @RequestBody Organizer organizer) {
        Map<String, Object> result = new HashMap<>();
        String token = request.getHeader("token");

        if (token == null || token.isEmpty()) {
            result.put("success", false);
            result.put("msg", "未登录");
            return result;
        }

        // 获取当前登录用户
        Object organizerObj = SimpleTokenUtils.getUserByToken(token);
        Organizer currentUser = null;
        if (organizerObj instanceof Organizer) {
            currentUser = (Organizer) organizerObj;
        }

        if (currentUser == null) {
            result.put("success", false);
            result.put("msg", "登录已过期，请重新登录");
            return result;
        }

        // 确保用户只能更新自己的信息
        if (!currentUser.getOrId().equals(organizer.getOrId())) {
            result.put("success", false);
            result.put("msg", "无权限修改其他用户信息");
            return result;
        }

        // 如果要更新账号，需要检查是否与其他用户账号重复
        if (organizer.getOrAccount() != null && !organizer.getOrAccount().equals(currentUser.getOrAccount())) {
            // 查询是否有其他用户使用了这个账号
            QueryWrapper<Organizer> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("or_account", organizer.getOrAccount());
            Organizer existingOrganizer = organizerService.getOne(queryWrapper);
            if (existingOrganizer != null) {
                result.put("success", false);
                result.put("msg", "该账号已被其他用户使用");
                return result;
            }
        }

        // 调用服务更新信息
        boolean success = organizerService.updateOrganizerInfo(organizer);
        if (success) {
            result.put("success", true);
            result.put("msg", "信息更新成功，请重新登录");

            SimpleTokenUtils.removeToken(token);
        } else {
            result.put("success", false);
            result.put("msg", "信息更新失败");
        }

        return result;
    }
    
    /**
     * 删除报名信息，如果删除的是已通过审批的报名信息，则项目参赛人数减一
     */
    @DeleteMapping("/deleteReg")
    public Map<String, Object> deleteRegistration(HttpServletRequest request, 
                                                 @RequestParam Integer regId) {
        Map<String, Object> result = new HashMap<>();
        String token = request.getHeader("token");

        if (token == null || token.isEmpty()) {
            result.put("success", false);
            result.put("msg", "未登录");
            return result;
        }

        // 获取当前登录用户
        Object organizerObj = SimpleTokenUtils.getUserByToken(token);
        Organizer currentUser = null;
        if (organizerObj instanceof Organizer) {
            currentUser = (Organizer) organizerObj;
        }

        if (currentUser == null) {
            result.put("success", false);
            result.put("msg", "登录已过期，请重新登录");
            return result;
        }

        // 调用服务删除报名信息
        boolean success = ((OrganizerService) organizerService).deleteRegistration(regId);
        if (success) {
            result.put("success", true);
            result.put("msg", "报名信息删除成功");
        } else {
            result.put("success", false);
            result.put("msg", "报名信息删除失败");
        }

        return result;
    }
    
    /**
     * 审批通过用户报名申请，并增加对应项目对象的当前人数
     */
    @PostMapping("/approveReg")
    public Map<String, Object> approveRegistration(HttpServletRequest request,
                                                  @RequestParam Integer regId) {
        Map<String, Object> result = new HashMap<>();
        String token = request.getHeader("token");

        if (token == null || token.isEmpty()) {
            result.put("success", false);
            result.put("msg", "未登录");
            return result;
        }

        // 获取当前登录用户
        Object organizerObj = SimpleTokenUtils.getUserByToken(token);
        Organizer currentUser = null;
        if (organizerObj instanceof Organizer) {
            currentUser = (Organizer) organizerObj;
        }

        if (currentUser == null) {
            result.put("success", false);
            result.put("msg", "登录已过期，请重新登录");
            return result;
        }

        // 调用服务审批报名信息
        boolean success = ((OrganizerService) organizerService).approveRegistration(regId);
        if (success) {
            result.put("success", true);
            result.put("msg", "报名信息审批通过成功");
        } else {
            result.put("success", false);
            result.put("msg", "报名信息审批通过失败");
        }

        return result;
    }
}
